import datetime
import json
import talib

import numpy as np
import os

import baostock as bs
import pandas as pd

# Create your views here.
from django.core.paginator import Paginator
from django.db.models import Count
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from yaml import serialize

from chartstest.datasViews import connectushare
from chartstest.models import TusharDate, DealDetail, stock_basic, cctv_news, coinInfo
import tushare as ts

from utils.MyEncoder import MyEncoder


def digitalCashIndex(request):
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)
    # tscode 分组
    # result = coinInfo.objects.values('id').annotate(Count=Count('tscode')).order_by('-id')[:3]
    result = coinInfo.objects.all()
    print(type(result))
    # print(result.count())

    for obj in result:
        # print(obj)
        data_list.append(obj)

    # for i in range(0, len(book_list)):
    #     #data_list.append(book_list[i][9])
    #     print(i)
    # print(book_list.count())

    # print("json:" + json.dumps(data_list))
    # print(data_list)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'digitalCash/index.html')


# 在处理函数加此装饰器即可
@csrf_exempt
def downDate(request):
    # 从tushare查询某只股票日线数据
    # pro = connectushare
    # 查询当前所有正常上市交易的股票列表
    pro = ts.pro_api('09c23ca7df4d6e0692459fd98de6207c1d687158fb1e946f5be77af8')

    pd.set_option('display.max_columns', None)

    datas = pro.coinlist(start_date='20170101', end_date='20171231')
    # 将date值转换为datetime类型，并且设置成index
    # datas.index = datas.date
    # dataform 转成list
    train_data = np.array(datas)  # np.ndarray()
    train_x_list = train_data.tolist()  # list
    # print(train_x_list)
    # 数据排序，正序
    train_x_list.sort(key=lambda x: x[0], reverse=True)

    for i in range(1, len(train_x_list)):
        tt = train_x_list[i]
        print(tt)
        print("时间:" + train_x_list[i][0])
        print("标题:" + train_x_list[i][1])
        c = coinInfo()
        c.coin = train_x_list[i][0]
        c.en_name = train_x_list[i][1]
        c.cn_name = train_x_list[i][2]

        c.issue_date = train_x_list[i][3]
        if tt[4] == "nan":
            c.issue_price = 0
        else:
            c.issue_price = train_x_list[i][4]

        '''
       
        c.amount = train_x_list[i][5]

        c.supply = train_x_list[i][6]
        c.algo = train_x_list[i][7]
        c.area = train_x_list[i][8]

        c.desc = train_x_list[i][9]
        c.labels = train_x_list[i][10]
         '''

        c.save()



    digital_list = {'code': 0, 'msg': 'success', 'data': ""}
    return JsonResponse(digital_list)


# 用户数据
@csrf_protect
@xframe_options_exempt
def digital_date(request):
    page = request.GET.get('page')  # 页面
    limit = request.GET.get('limit')  # 条数
    print(page)
    print(limit)
    digital_list = {}
    r = coinInfo.objects.all();
    datas = list(r)
    page_inator = Paginator(datas, limit)  # 分页
    contacts = page_inator.page(page)  # 请求第几页数据
    res = []  # 最终返回的结果集合
    for p in contacts:
        dic = {}
        dic['id'] = p.id
        dic['coin'] = p.coin
        dic['en_name'] = p.en_name
        dic['cn_name'] = p.cn_name
        dic['issue_date'] = p.issue_date
        dic['issue_price'] = p.issue_price
        dic['amount'] = p.amount
        dic['supply'] = p.supply
        dic['algo'] = p.algo
        dic['area'] = p.area
        dic['labels'] = p.labels
        dic['desc'] = p.desc
        res.append(dic)

    print(res)
    digital_list['code'] = 0
    digital_list['msg'] = 'success'
    digital_list['data'] = res
    digital_list['count'] = coinInfo.objects.all().count()
    return JsonResponse(digital_list)
